<template>
	<view class="container">
		<view class="header">
			<view class="title">报价</view>
		</view>

		<view class="content">
			<view class="info-group">
				<view class="info-item">
					<text class="label">采购单:</text>
					<text class="value">{{ auctionInfo.title }}</text>
				</view>
				<view class="info-item">
					<text class="label">起始价:</text>
					<text class="value price">¥{{ auctionInfo.start_price }}</text>
				</view>
				<view class="info-item">
					<text class="label">截止时间:</text>
					<text class="value">{{ formatDate(auctionInfo.end_time) }}</text>
				</view>
			</view>

			<view class="my-bid-info">
				<template v-if="myBid">
					<view class="info-item">
						<text class="label">我当前的报价:</text>
						<text class="value price">¥{{ myBid.amount }}</text>
					</view>
					<view class="info-item">
						<text class="label">我当前的排名:</text>
						<text class="value rank">第 {{ myRank }} 名</text>
					</view>
				</template>
				<template v-else>
					<view class="info-item no-bid">
						<text class="value">您还未报价</text>
					</view>
				</template>
			</view>

			<view class="form-group">
				<view class="form-item">
					<text class="label">{{ myBid ? '输入新报价' : '报价金额' }}</text>
					<input class="input" type="digit" v-model="formData.amount" placeholder="请输入报价金额" />
				</view>
				<view class="tip">
					<text class="tip-text">注意：报价必须低于起始价格。修改报价时，新报价必须更低。</text>
				</view>
			</view>

			<view class="action-bar">
				<button class="action-btn submit-btn" @click="submit">{{ myBid ? '修改报价' : '提交报价' }}</button>
				<button class="action-btn back-btn" @click="navigateBack">返回</button>
			</view>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database();
	const bidsCollectionName = 'bids';
	const auctionsCollectionName = 'auctions';

	export default {
		data() {
			return {
				auctionId: '',
				auctionInfo: {},
				formData: {
					amount: null
				},
				myBid: null,
				myRank: 0
			}
		},
		onLoad(e) {
			if (e.auctionId) {
				this.auctionId = e.auctionId
				this.loadAuctionInfo()
			}
		},
		methods: {
			loadAuctionInfo() {
				db.collection(auctionsCollectionName).doc(this.auctionId).get().then((res) => {
					const data = res.result.data[0]
					if (data) {
						this.auctionInfo = data
						this.loadMyBidInfo();
					}
				}).catch((err) => {
					uni.showModal({
						content: '加载采购单信息失败: ' + err.message,
						showCancel: false
					})
				})
			},
			      loadMyBidInfo() {
        const tokenExpired = uniCloud.getCurrentUserInfo().tokenExpired;
        if (!tokenExpired || tokenExpired < Date.now()) {
          return uni.showModal({
            title: '提示',
            content: '您的登录已过期，请重新登录',
            showCancel: false,
            success: () => {
              uni.navigateTo({
                url: "/uni_modules/uni-id-pages/pages/login/login-withoutpwd"
              });
            }
          });
        }

				uniCloud.callFunction({
					name: 'getBidInfoForSupplier',
					data: {
						auctionId: this.auctionId
					}
				}).then(res => {
					if (res.result.errCode === 0) {
						const { myBid, myRank } = res.result.data;
						if (myBid) {
							this.myBid = myBid;
							this.myRank = myRank;
							this.formData.amount = myBid.amount;
						}
					} else {
						console.error(res.result.errMsg);
					}
				}).catch(err => {
					console.error("加载报价信息失败", err);
				})
			},
			formatDate(timestamp) {
				if (!timestamp) return ''
				const date = new Date(timestamp)
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
			},
			submit() {
				if (!this.formData.amount) {
					return uni.showToast({ title: '请输入报价金额', icon: 'none' })
				}
				const amount = parseFloat(this.formData.amount)
				if (isNaN(amount)) {
					return uni.showToast({ title: '请输入有效的金额', icon: 'none' })
				}
				if (amount >= this.auctionInfo.start_price) {
					return uni.showToast({ title: '报价必须低于起始价格', icon: 'none' })
				}
				if (this.myBid && amount >= this.myBid.amount) {
					return uni.showToast({ title: '新报价必须低于您之前的报价', icon: 'none' });
				}
				if (this.auctionInfo.end_time && Date.now() > this.auctionInfo.end_time) {
					return uni.showModal({ title: '提示', content: '该采购单已过报价截止时间，无法提交报价', showCancel: false })
				}

				uni.showLoading({ mask: true, title: '提交中...' })

				if (this.myBid) {
					// 更新报价
					db.collection(bidsCollectionName).doc(this.myBid._id).update({
						amount: amount,
						timestamp: Date.now()
					}).then(res => {
						uni.showToast({ title: '报价修改成功', icon: 'success' });
						setTimeout(() => uni.navigateBack(), 1500);
					}).catch(err => {
						uni.showModal({ title: '提交失败', content: err.message || '请求服务失败', showCancel: false });
					}).finally(() => uni.hideLoading());
				} else {
					// 新增报价
					const submitData = {
						auction_id: this.auctionId,
						amount: amount
					};
					db.collection(bidsCollectionName).add(submitData).then((res) => {
						uni.showToast({ title: '报价提交成功', icon: 'success' });
						setTimeout(() => uni.navigateBack(), 1500);
					}).catch((err) => {
						uni.showModal({ title: '提交失败', content: err.message || '请求服务失败', showCancel: false });
					}).finally(() => uni.hideLoading());
				}
			},
			navigateBack() {
				uni.navigateBack()
			}
		}
	}
</script>

<style scoped>
	.container {
		padding: 20rpx;
	}
	.header {
		margin-bottom: 30rpx;
	}
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	.content {
		background-color: white;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
		padding: 30rpx;
	}
	.info-group, .my-bid-info {
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	.info-item {
		margin-bottom: 20rpx;
	}
	.info-item:last-child {
		margin-bottom: 0;
	}
	.label {
		font-weight: bold;
		color: #333;
		display: inline-block;
		width: 180rpx;
	}
	.value {
		color: #666;
		font-size: 28rpx;
	}
	.value.price {
		color: #ff4d4f;
		font-size: 32rpx;
		font-weight: bold;
	}
	.value.rank {
		color: #007AFF;
		font-weight: bold;
	}
	.no-bid {
		text-align: center;
		color: #999;
	}
	.form-group {
		margin-bottom: 40rpx;
	}
	.form-item .label {
		display: block;
		font-weight: bold;
		color: #333;
		margin-bottom: 15rpx;
	}
	.input {
		padding: 20rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 10rpx;
		font-size: 28rpx;
	}
	.tip {
		background-color: #fffbe6;
		border: 1rpx solid #ffe58f;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-top: 20rpx;
	}
	.tip-text {
		color: #faad14;
		font-size: 24rpx;
	}
	.action-bar {
		display: flex;
		justify-content: center;
	}
	.action-btn {
		padding: 20rpx 40rpx;
		font-size: 28rpx;
		border-radius: 10rpx;
		margin: 0 20rpx;
	}
	.submit-btn {
		background-color: #007AFF;
		color: white;
	}
	.back-btn {
		background-color: #f0f0f0;
		color: #333;
	}
</style>